package com.xunfang.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.xunfang.bean.User;
import com.xunfang.bean.dto.LoginUserDTO;
import com.xunfang.mapper.UserMapper;
import com.xunfang.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author yellow Docter
 * @date 2023 -10-25
 * @desc
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(LoginUserDTO user) {
        //传入进来的: user {username=admin，password=123}

        User u= userMapper.login(user.getUsername());
        //传入进来的: user {username=lisi，password=1234}

        //进行密码校验
        // password=1234  和 ，password=123
//        if (u.getPassword().equals(user.getPassword())){
//            // user {username=lisi，password=1234}
//            return u;
//        }
        //输入的加密  比对  数据库的密码
        boolean checkpw = BCrypt.checkpw(user.getPassword(), u.getPassword());
        if (checkpw){

            //验证通过存储用户 session
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpSession session = requestAttributes.getRequest().getSession();
            session.setAttribute("user",u);

            return u;
        }
        return null;
    }
}
